// @ts-nocheck
import router from '../router/index';
import { useRoute } from 'vue-router';

// import Pinyin from 'pinyin';

const gethidePhone = (phone: string): string => {
  let number = phone; //获取到手机号码字段
  // console.log('手机号', this.tel)
  let mphone = number.substring(0, 3) + '****' + number.substring(7);
  return mphone;
};
const convertToPinyin = (text: string) => {
  // if (text) {
  //   let str = Pinyin(text, {
  //     style: Pinyin.STYLE_NORMAL,
  //   }).join(' ');
  //   return str;
  // } else {
  //   return '';
  // }
  return '';
};
// http://101.34.143.36:8890/api/image
const imgLinkUrl = (url: string): string => {
  return 'http://file.wuzhan.art/api/image/' + url;
};
const handlemouse = (e: string) => {
  const nav = document.getElementById(e);
  if (!nav) {
    return;
  }
  var flag;
  var downX; // 鼠标点击的x下标
  var scrollLeft; // 当前元素滚动条的偏移量
  nav.addEventListener('mousedown', function (event) {
    flag = true;
    downX = event.clientX; // 获取到点击的x下标
    scrollLeft = this.scrollLeft; // 获取当前元素滚动条的偏移量
    event.stopPropagation();
  });
  nav.addEventListener('mousemove', function (event) {
    if (flag) {
      // 判断是否是鼠标按下滚动元素区域
      var moveX = event.clientX; // 获取移动的x轴
      var scrollX = moveX - downX; // 当前移动的x轴下标减去刚点击下去的x轴下标得到鼠标滑动距离
      this.scrollLeft = scrollLeft - scrollX; // 鼠标按下的滚动条偏移量减去当前鼠标的滑动距离
      // console.log(scrollX);
      event.stopPropagation();
    }
  });

  nav.addEventListener('touchmove', function (event) {
    event.stopPropagation();
    nav.addEventListener(
      'touchmove',
      function (event) {
        event.preventDefault(); // 阻止默认的滚动行为
        var touch = event.targetTouches[0];
        var deltaX = touch.clientX - startX; // 计算滚动的距离
        container.scrollLeft -= deltaX; // 将盒子滚动相应的距离
        startX = touch.clientX; // 更新触摸点的位置
      },
      { passive: false },
    );
    // event.stopPropagation(); // 阻止事件冒泡
    // event.preventDefault(); // 阻止默认滚动事件
    // const touch = event.touches[0]; // 获取第一个触点
    // box.scrollTop += startY - touch.clientY; // 移动盒子
    // startY = touch.clientY; // 重置起始位置
  });
  const handler = (event: any) => {
    // 获取滚动方向
    const detail = event.wheelDelta || event.detail;
    // 定义滚动方向，其实也可以在赋值的时候写
    const moveForwardStep = 1;
    const moveBackStep = -1;
    // 定义滚动距离
    let step = 0;
    // 判断滚动方向,这里的100可以改，代表滚动幅度，也就是说滚动幅度是自定义的
    if (detail < 0) {
      step = moveForwardStep * 100;
    } else {
      step = moveBackStep * 100;
    }
    // 对需要滚动的元素进行滚动操作
    nav.scrollLeft += step;
    event.stopPropagation();
  };

  nav.addEventListener('mousewheel', handler, false);

  // 鼠标抬起停止拖动
  nav.addEventListener('touchmove', function (event) {
    event.stopPropagation(); // 阻止事件冒泡
    event.preventDefault(); // 阻止默认滚动事件
  });
  nav.addEventListener('mouseup', function (event) {
    flag = false;
    event.stopPropagation();
  });
  // 鼠标离开元素停止拖动
  nav.addEventListener('mouseleave', function (event) {
    flag = false;
    event.stopPropagation();
  });
};
const pathSquare = (e: number, loopType?: any) => {
  //通过id以及模式 前往要跳转的模版
  // const url = window.location.href; 
  // const searchString = '/square';
  // if (url.indexOf(searchString) !== -1) {
  //   return; 
  // }
  // square

  let projactId = localStorage.getItem('projectId');
  let linkUrl: string = '';
  if (!e && loopType) { 
    linkUrl = `/edit/${projactId}/square`;
  }
  linkUrl = loopType ? `/edit/${projactId}/wylx/home` : `/web/${projactId}/wylx/home`;

  let newUrl = '';
  const isMobile = navigator.userAgent.match(
    /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i,
  );
  if (isMobile) {
    //判断是否是移动端情况
    linkUrl = `/wap/${projactId}/wylx/home`;
      newUrl = linkUrl;
      
    
  } else {
    linkUrl = `/web/${projactId}/wylx/home`;
    newUrl = linkUrl;
  }
  console.log(e, '++', newUrl);
  return newUrl;
};
const handler = (event: any) => {
  // 获取滚动方向
  const detail = event.wheelDelta || event.detail;
  // 定义滚动方向，其实也可以在赋值的时候写
  const moveForwardStep = 1;
  const moveBackStep = -1;
  // 定义滚动距离
  let step = 0;
  // 判断滚动方向,这里的100可以改，代表滚动幅度，也就是说滚动幅度是自定义的
  if (detail < 0) {
    step = moveForwardStep * 100;
  } else {
    step = moveBackStep * 100;
  }
  nav.addEventListener('touchmove', function (event) {
    event.stopPropagation(); // 阻止事件冒泡
    event.preventDefault(); // 阻止默认滚动事件
  });
  // 对需要滚动的元素进行滚动操作
  nav.scrollLeft += step;
  event.stopPropagation();
};

const outLogin = (e?: string): any => {
  // window.location.href = e;
  router.push({ path: '/login' });
};
const getTextHtml = (e: string | null): any => {
  //获取文本域转换成标签
  if (!e) {
    return;
  }
  let arr = e.split('\n');
  let text = '';
  arr.forEach((el) => {
    if (el) {
      text = text + `<p>${el}</p>`;
    }
  });
  return text;
  // router.push({ path: '/login' });
};
const getTextHtmlBr = (e: string | null): any => {
  //模版一专用
  if (!e) {
    return;
  }
  let arr = e.split('\n');
  let text = '';
  arr.forEach((el) => {
    if (el) {
      text = text + `<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;${el}`;
    }
  });
  return text;
  // router.push({ path: '/login' });
};
const getTextHtmlellipsisBr = (e: string | null): any => {
  //模版一专用
  if (!e) {
    return;
  }
  let arr = e.split('\n');
  let text = '';
  arr.forEach((el, index) => {
    if (el && index !== 0) {
      text = text + `\n      ${el}`;
    } else {
      text = text + `${el}`;
    }
  });
  return text;
  // router.push({ path: '/login' });
};
const filterHTML = (input: string) => {
  let str = input.replace(/(<([^>]+)>)/gi, '');
  str = str.replace(/&ldquo;/gi, '');
  return str.replace(/&rdquo;/g, '');
};

const pagerCount = (count: number, pageSize: number) => {
  if (typeof count == 'number') {
    if (count > 0) {
      try {
        let _pagerCount: number = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
        let c = Number(_pagerCount.toFixed(0)); //小数取整
        _pagerCount = c > _pagerCount ? c - 1 : c; //过滤四舍五入
        return Number(_pagerCount);
      } catch (error) {
        return 0;
      }
    } else {
      return 0;
    }
  } else {
    return 0;
  }
};
const formatFileSize = (size: number | string) => {
  if (size >= 1024) {
    return (size / 1024).toFixed(1) + 'M';
  } else {
    return size.toFixed(1) + 'K';
  }
};
const getTrimText = (str?: string) => {
  if (!str) {
    return '';
  }
  var result = str.replace(/\s/g, '');
  return result;
};

const titleSubsection = (title: string, index?: number) => {
  //将文字分段处理 import {titleSubsection} from "@/utils/minxin"
  // 移除文本两端的空格

  let text = title.trim();
  if (text.length <= 8) {
    return text;
  }
  if (index && text.length <= index) {
    return text;
  }
  // 尝试按空格分割文本
  let midIndex = Math.ceil(text.length / 2); // 使用Math.ceil确保第二行不会太短

  // 如果直接分割会导致第二行过短（例如文本长度为9时），则将中点向后移动
  if (midIndex * 2 < text.length) {
    midIndex++;
  }

  // 分割文本为两行
  let firstLine = text.substring(0, midIndex);
  let secondLine = text.substring(midIndex);
  return `${firstLine}</br>${secondLine}`;
};
let ImgUrlCancat = '//static.jiyi.show';
let doorUrl: string = 'https://t-www.youxinjiyi.com/';
let editUlrs: string = 'https://t-www.youxinjiyi.com/frame/#/exhibition?projectId=';
let workbenchUrl: string = 'http://t-workbench.youxinjiyi.com/#/';
let cancatUrl: string = 'https://t-www.youxinjiyi.com/ex/#/';
if (import.meta.env.MODE !== 'development') {
  cancatUrl = '//www.jiyi.show/ex/#/';
  ImgUrlCancat = '//static.jiyi.show';
  doorUrl = '//www.jiyi.show/';
  editUlrs = '//www.jiyi.show/frame/#/exhibition?projectId=';
  workbenchUrl = '//workbench.jiyi.show/#/';
}
const getPageScrollType = (e: number | string) => {
  //配置当前页面是否不进行内部滚动 e:当前模版id
  switch (e) {
    case 1997:
      return true;
      break;
    case 395740859879493:
      return true;
      break;

    default:
      return false;
  }
};
const getUrlTemplateId = () => {
  const url = window.location.href;
  const regex = /\/(\d+)/; // 匹配数字参数的正则表达式
  const match = url.match(regex); // 使用正则表达式匹配数字参数

  if (match) {
    const numericParam = parseInt(match[1]); // 提取数字参数并将其转换为数字类型
    // alert(numericParam);
    // console.log(numericParam); // 输出数字参数的值
    localStorage.setItem('projectId', String(numericParam));
    return numericParam;
  } else {
    return;
    // window.location.href = doorUrl;
  }
};
const removeLottie = () => {
  var element = document.getElementById('animationElement-lottieMove');
  // var parent = element.parentNode;
  setTimeout(() => {
    if (element) {
      element.style.opacity = 0;
    }
  }, 600);

  setTimeout(() => {
    // parent.removeChild(element);

    if (element) {
      element.remove();
    }
  }, 1600);
};
const isURL = (input) => {
  // 匹配URL的正则表达式
  var urlPattern = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i;

  // 判断输入是否匹配正则表达式
  return urlPattern.test(input);
};
const dataURLtoFile = (dataurl, filename) => {
  let arr = dataurl.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, {
    type: mime,
  });
};
const publicUrls: string = 'https://static.jiyi.show/';
export {
  dataURLtoFile,
  getTextHtmlellipsisBr,
  isURL,
  cancatUrl,
  publicUrls,
  formatFileSize,
  removeLottie,
  workbenchUrl,
  getTrimText,
  editUlrs,
  doorUrl,
  ImgUrlCancat,
  getUrlTemplateId,
  pagerCount,
  handler,
  getTextHtml,
  pathSquare,
  outLogin,
  gethidePhone,
  imgLinkUrl,
  handlemouse,
  filterHTML,
  convertToPinyin,
  getPageScrollType,
  titleSubsection,
  getTextHtmlBr,
};
